<?php

namespace app\admin\controller\routine;



use app\common\controller\Backend;

class ScheduledTask extends Backend
{

    protected bool $limitSiteId = false;



    public function initialize(): void
    {
        parent::initialize();
        $this->model = new \app\common\model\ScheduledTasks();
    }



    /**
     * 查看
     */
    public function index(): void
    {
        if ($this->request->param('select')) {
            $this->select();
        }

        list($where, $alias, $limit, $order) = $this->queryBuilder();
        $res = $this->model
            ->field($this->indexField)
            ->withJoin($this->withJoinTable, $this->withJoinType)
            ->alias($alias)
            ->where($where)
            ->order($order)
            ->paginate($limit);

        $thinkFile = root_path() . 'think';
        $this->success('', [
            'list'   => $res->items(),
            'total'  => $res->total(),
            'remark' => "需要宝塔开启计划任务/每分钟执行脚本：`php {$thinkFile} dispatch`，Linux计划任务：`* * * * * php {$thinkFile} dispatch`"
        ]);
    }


    /**
     * 运行
     * @return void
     */
    public function run()
    {
        $pk  = $this->model->getPk();
        $id  = $this->request->param($pk);
        $row = $this->model->find($id);
        if (!$row) {
            $this->error(__('Record not found'));
        }

        if(!class_exists($row->class_name)){
            $this->error(__('Class not found'));
        }

        try {
            $class = new $row->class_name();
            $class->run(true, $row->params ?? []);
        } catch (\Exception|\Throwable $e) {
            $this->error($e->getMessage());
        }

        $this->success('运行成功！');
    }



}